package com.goldsprite.microhorigame.ecs;

import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.*;
import com.badlogic.gdx.math.*;
import com.badlogic.gdx.utils.*;
import com.goldsprite.gameframeworks.assets.*;
import com.goldsprite.gameframeworks.ecs.*;
import com.goldsprite.gameframeworks.ecs.component.*;
import com.goldsprite.gameframeworks.ecs.system.*;
import com.goldsprite.gameframeworks.utils.*;

public class ParallaxBackgroundComponent extends SpriteComponent {
	private OrthographicCamera cam;
	private final Array<ParallaxLayer> layers = new Array<>();
	private Vector3 followTarget;
	private Vector2 entityTarget;

	private Vector2 diffCamPos = new Vector2();
	private Vector2 camStartPos = new Vector2();

	// 视差配置
	private boolean enabled = true;
	private float baseScrollSpeed = 0f; // 基础滚动速度（用于自动滚动）

	public ParallaxBackgroundComponent() {
		cam = GameSystem.worldCamera;
		setSpriteLayer("FarBackground");
		setPivot(Pivot.Center);
	}

	public void setCamStartPos(Vector2 sPos) {
		camStartPos = new Vector2(sPos);
	}

	/**
	 * 添加视差图层
	 *
	 * @param region         纹理区域
	 * @param parallaxFactor 视差系数 (0-1)，0=静止，1=跟随相机
	 * @param position       初始位置
	 * @param scale          缩放
	 */
	public void addLayer(TextureRegion region, float parallaxFactor, Vector2 position, float scale) {
		addLayer(region, new Vector2(parallaxFactor, parallaxFactor), position, scale);
	}

	/**
	 * 添加视差图层（支持XY轴不同视差系数）
	 */
	public void addLayer(TextureRegion region, Vector2 parallaxFactor, Vector2 position, float scale) {
		ParallaxLayer layer = new ParallaxLayer();
		//uv采样误差修正
//		float fix = 0.001f;
//		region.setRegion(region.getU() + fix, region.getV() + fix, region.getU2() - fix, region.getV2() - fix);
		layer.region = region;
		layer.parallaxFactor = parallaxFactor;
		layer.startPosition = new Vector2(position);
		layer.currentPosition = new Vector2(position);
		layer.scale = scale;
		layer.regionWidth = region.getRegionWidth();
		layer.regionHeight = region.getRegionHeight();

		layers.add(layer);
	}

	/**
	 * 添加平铺图层（左右平铺多个纹理来覆盖整个视口）
	 *
	 * @param tileCount      平铺数量（通常为3：左中右）
	 * @param region         纹理区域
	 * @param parallaxFactor 视差系数
	 * @param startPosition  起始位置
	 * @param scale          缩放
	 */
	public void addMultiLayer(int tileCount, TextureRegion region, Vector2 parallaxFactor, Vector2 startPosition, float scale) {
		float regionWidth = region.getRegionWidth();

		int addditveCount = Math.max(1, tileCount - 1);
		for (int i = -addditveCount / 2; i < addditveCount; i++) {
			// 计算每个平铺的位置（水平排列）
			Vector2 tilePosition = new Vector2(startPosition);
			tilePosition.x += i * regionWidth;

			// 添加图层
			addLayer(region, parallaxFactor, tilePosition, scale);
		}
	}

	/**
	 * 添加平铺图层（简化版本）
	 */
	public void addMultiLayer(int tileCount, TextureRegion region, float parallaxFactor, Vector2 startPosition, float scale) {
		addMultiLayer(tileCount, region, new Vector2(parallaxFactor, parallaxFactor), startPosition, scale);
	}

	/**
	 * 从资源添加多个图层
	 */
	public void addLayersFromResource(GameRes resource, int startFrame, int frameCount, float[] parallaxFactors) {
		SpriteUtils.setUVUnit(resource.getUVUnit());
		Array<TextureRegion> regions = SpriteUtils.splitFrames(resource, startFrame, frameCount);

		for (int i = 0; i < Math.min(regions.size, parallaxFactors.length); i++) {
			addLayer(regions.get(i), parallaxFactors[i], new Vector2(cam.position.x - cam.viewportWidth / 2f, cam.position.y - cam.viewportHeight / 2f), 1f);
		}
	}

	/**
	 * 设置跟随目标（相机）
	 */
	public void setFollowTarget(Vector3 target) {
		this.followTarget = target;
		this.entityTarget = null;
	}

	/**
	 * 设置跟随目标（实体位置）
	 */
	public void setFollowTargetByEntity(Vector2 position) {
		this.entityTarget = position;
		this.followTarget = null;
	}

	/**
	 * 设置基础滚动速度（用于自动背景滚动）
	 */
	public void setBaseScrollSpeed(float speed) {
		this.baseScrollSpeed = speed;
	}

	/**
	 * 启用/禁用视差效果
	 */
	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	@Override
	public void update(float delta) {
		super.update(delta);

		if (!enabled) return;

		// 获取目标位置
		Vector3 targetPos = getTargetPosition();

		// 更新所有图层位置
		for (ParallaxLayer layer : layers) {
			updateLayerPosition(layer, targetPos, delta);
		}
	}

	@Override
	public void render(Batch batch, float delta) {
		if (!enabled) return;

		// 保存当前状态
		TextureRegion originalRegion = getRegion();
		Vector2 originalPosition = new Vector2(getTransform().getPosition());
		Vector2 originalScale = new Vector2(getScale());

		// 渲染所有图层
		for (ParallaxLayer layer : layers) {
			setRegion(layer.region);
			getTransform().getPosition().set(layer.currentPosition);
			getScale().set(layer.scale);
			super.render(batch, delta);
		}

		// 恢复状态
		setRegion(originalRegion);
		getTransform().getPosition().set(originalPosition);
		getScale().set(originalScale);
	}

	private Vector3 getTargetPosition() {
		if (followTarget != null) {
			return followTarget;
		} else if (entityTarget != null) {
			return new Vector3(entityTarget.x, entityTarget.y, 0);
		} else {
			// 默认使用相机位置
			return new Vector3(cam.position.x, cam.position.y, 0);
		}
	}

	private void updateLayerPosition(ParallaxLayer layer, Vector3 targetPos, float delta) {
		//layer.currentPosition.x = layer.startPosition.x*layer.scale + cam.position.x;

		diffCamPos.set(cam.position.x, cam.position.y).sub(camStartPos);
		layer.currentPosition.x = layer.startPosition.x * layer.scale + diffCamPos.x * layer.parallaxFactor.x;
		layer.currentPosition.y = layer.startPosition.y * layer.scale + diffCamPos.y * layer.parallaxFactor.y;
	}

	/**
	 * 获取图层数量
	 */
	public int getLayerCount() {
		return layers.size;
	}

	/**
	 * 获取指定图层
	 */
	public ParallaxLayer getLayer(int index) {
		if (index >= 0 && index < layers.size) {
			return layers.get(index);
		}
		return null;
	}

	/**
	 * 清除所有图层
	 */
	public void clearLayers() {
		layers.clear();
	}

	/**
	 * 视差图层数据类
	 */
	public static class ParallaxLayer {
		public TextureRegion region;
		public Vector2 parallaxFactor = new Vector2(1f, 1f); // XY轴视差系数
		public Vector2 startPosition = new Vector2();        // 初始位置
		public Vector2 currentPosition = new Vector2();      // 当前位置
		public float scale = 1f;                            // 缩放
		public float regionWidth;                           // 区域宽度
		public float regionHeight;                          // 区域高度
	}
}
